const express = require("express");
const formidable = require("formidable");
const fs = require("fs");
const app = express();

app.post("/upload",(req,res) =>{
    const form = new formidable.IncomingForm();
    form.uploadDir = "./temp";
    form.maxFileSize = 5 * 1024 * 1024 *1024;//5G
    form.parse(req,(err,fields,files) => {
        if(err) {
            console.log(err);
            res.end("err");
        } else {
            console.log(files);
            console.log(files.file.path);
            const file = files&&files.file
            if(file) {
                fs.writeFile(`public/${files.file.name}`,fs.readFileSync(files.file.path),e=>{
                    console.log(e);
                })
                res.json("ok");
                res.end();
            } else {
                res.json("err");
                res.end();
            }
        }
        
    })
});

//指定静态文件
app.use(express.static("public"))

const server = app.listen(3000,() =>{
    const host = server.address().address;
    const port = server.address().port;
    console.log('upload app listening at http://%s:%s', host, port);
})
